package com.plantplaces.dao;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.plantplaces.dto.Plant;
import com.plantplaces.dto.PlantSearch;

public class PlantDAOImpl implements IPlantDAO {

	// declare network dao.
	INetworkDAO networkDAO;
	
	public PlantDAOImpl() {
		networkDAO = new NetworkDAO();
	}
	
	/**
	 * Parse a String of data to a JSON object, then convert that JSON object to a list of Plant objects.
	 */
	@Override
	public List<Plant> fetchPlants(PlantSearch ps) throws Exception {

		// Declare a return collection.
		ArrayList<Plant> allPlants = new ArrayList<Plant>();
		
		// the query URI we wish to access.
		String uri = "http://plantplaces.com/perl/mobile/viewplantsjson.pl?Combined_Name=" + ps.getCommon();
		
		// result will hold the JSON data.
		String result = networkDAO.request(uri);
		
		// parse the JSON data. 
		JSONObject root = new JSONObject(result);
		
		// ask the JSONObject for the array that it contains.
		JSONArray plantsArray = root.getJSONArray("plants");

		// old school for loop.
		for (int i = 0; i < plantsArray.length(); i++) {
			// convert the JSON object at this iteration position to a Plant object.
			JSONObject plantJSON = plantsArray.getJSONObject(i);
			
			// declare a new plant object.
			Plant thisPlant = new Plant();
			
			// copy data from the JSON object to the plant object.
			int id = plantJSON.getInt("id");
			thisPlant.setId(id);
			
			String genus = plantJSON.getString("genus");
			thisPlant.setGenus(genus);
			
			String species = plantJSON.getString("species");
			thisPlant.setSpecies(species);
			
			String cultivar = plantJSON.getString("cultivar");
			thisPlant.setCultivar(cultivar);
			
			String common = plantJSON.getString("common");
			thisPlant.setCommon(common);
			
			// add this plant to a collection of plants that we will return.
			allPlants.add(thisPlant);
		}
		
		// TODO Auto-generated method stub
		return allPlants;
	}

	@Override
	public List<String> fetchPlantNames() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
